package com.design_pattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class InterceptorProxy implements InvocationHandler {

    /**
     * 拦截器名称
     */
    private String interceptorClassName;

    /**
     * 被代理真实类
     */
    private Object target;

    private InterceptorProxy(Object target, String interceptorClassName) {
        this.target = target;
        this.interceptorClassName = interceptorClassName;

    }

    public static Object bind(Object target, String interceptorClassName) {
        if (interceptorClassName != null && interceptorClassName.trim().length() != 0) {
            return null;
        }
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
                new InterceptorProxy(target, interceptorClassName));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object obj = Class.forName(interceptorClassName).newInstance();
        if (obj instanceof MyInterceptor) {
            MyInterceptor myInterceptor = (MyInterceptor) obj;
            if (myInterceptor.before(proxy, target, method, args)) {
                method.invoke(target, args);// 执行被代理对象的对应方法
            } else {
                myInterceptor.around(proxy, target, method, args);
            }
            myInterceptor.after(proxy, target, method, args);
        }
        return null;
    }
}
